package com.zyf.apitest.transform;

import com.zyf.apitest.beans.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import sun.management.Sensor;

/**
 * @author Malegod_xiaofei
 * @create 2021-12-27-20:36
 */
public class TransFormTest2_RollingAggregation {
    public static void main(String[] args) throws Exception {
        // 创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 设置并行度
        env.setParallelism(1);

        // 从文件读取数据
        DataStream<String> inputStream = env.readTextFile("D:\\Code\\IDEA-Project\\FlinkTutorial\\src\\main\\resources\\sensor.txt");

        // 转换成 SensorReading 类型
//        DataStream<SensorReading> map = inputStream.map(new MapFunction<String, SensorReading>() {
//            @Override
//            public SensorReading map(String value) throws Exception {
//                String[] fileds = value.split(",");
//                return new SensorReading(fileds[0], new Long(fileds[1]), new Double(fileds[2]));
//            }
//        });

        // 使用 lambda 表达式
        DataStream<SensorReading> dataStream = inputStream.map(line -> {
            String[] fileds = line.split(",");
            return new SensorReading(fileds[0], new Long(fileds[1]), new Double(fileds[2]));
        });

        // 分组
        KeyedStream<SensorReading, Tuple> kayedStream = dataStream.keyBy("id");
//        KeyedStream<SensorReading, String> kayedStream1 = dataStream.keyBy(SensorReading::getId);

        // 滚动聚合，取当前最大的温度值
        SingleOutputStreamOperator<SensorReading> resultStream = kayedStream.maxBy("temperature");

        resultStream.print("resultStream ");

        // 执行
        env.execute();
    }
}
